package com.shine.common.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shine.common.Constants;
import com.shine.common.web.model.SystemContext;

/**
 * 列表及分页参数设置
 * 
 * @author Administrator
 * 
 */
public class PaginationFilter implements Filter {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private FilterConfig config = null;

	private final String[] NULL_STRING_ARRAY = new String[0];
	private final String URL_SPLIT_PATTERN = "[, ;\r\n]";// 逗号 空格 分号 换行

	private String[] matchListURLs = null;

	@Override
	public final void init(FilterConfig config) throws ServletException {
		this.config = config;
		this.initConfig();
		this.init();
	}

	public void init() throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String currentURL = httpRequest.getServletPath();

        logger.debug("PaginationFilter filter : 当前URL : [{}]", currentURL);

        if (isWhiteURL(currentURL)) {
        	//设置分页参数
     		SystemContext.setCurrentPage(getCurrentPage(httpRequest));
     		SystemContext.setPageNumber(getPageNumber(httpRequest));
     		SystemContext.setDraw(getDraw(httpRequest));
     		
     		
     		
            chain.doFilter(request, response);
            return;
        }
        chain.doFilter(httpRequest, httpResponse) ;
        return;

	}
	
	private boolean isWhiteURL(String currentURL) {
        for (String whiteURL : matchListURLs) {
            if (currentURL.indexOf(whiteURL) != -1) {
                logger.debug("PaginationFilter filter : 匹配 : [{}] match [{}] continue", currentURL, whiteURL);
                return true;
            }
        }
        logger.debug("PaginationFilter filter : 不匹配 : [{}] not match [{}]", currentURL, Arrays.toString(matchListURLs));
        return false;
    }

	@Override
	public void destroy() {}

	private void initConfig() {
		String matchListURLStr = this.config.getInitParameter("matchListURL");
		matchListURLs = strToArray(matchListURLStr);

	}

	private String[] strToArray(String urlStr) {
		if (urlStr == null) {
			return NULL_STRING_ARRAY;
		}
		String[] urlArray = urlStr.split(URL_SPLIT_PATTERN);

		List<String> urlList = new ArrayList<String>();

		for (String url : urlArray) {
			url = url.trim();
			if (url.length() == 0) {
				continue;
			}

			urlList.add(url);
		}

		return urlList.toArray(NULL_STRING_ARRAY);
	}

	public FilterConfig getConfig() {
		return config;
	}
	
	//DataTables特有参数
	private int getDraw(HttpServletRequest request) {
		int draw = 1 ;
		if(null != request.getParameter("draw")) {
			draw = Integer.parseInt(request.getParameter("draw")) ;
		}
		return draw ;
	}
	
	private int getCurrentPage(HttpServletRequest request) {
		int currentPage = 0;
		try {
			if(null != request.getParameter("start")) {
				currentPage = Integer.parseInt(request.getParameter("start"));
			} 
			if(null != request.getParameter("iDisplayStart")) {
				currentPage = Integer.parseInt(request.getParameter("iDisplayStart"));
			} 
			//普通分页
			if(null != request.getParameter("currentPage")) {
				currentPage = Integer.parseInt(request.getParameter("currentPage")) - 1;
			} 
		} catch (Exception e) {
		}

		return currentPage;
	}

	private int getPageNumber(HttpServletRequest request) {
		int pageNumber = Constants.PAGE_NUMBER;
		try {
			if(null != request.getParameter("length")) {
				pageNumber = Integer.parseInt(request.getParameter("length"));
			}
			if(null != request.getParameter("iDisplayLength")) {
				pageNumber = Integer.parseInt(request.getParameter("iDisplayLength"));
			}
			//普通分页
			if(null != request.getParameter("pageSize")) {
				pageNumber = Integer.parseInt(request.getParameter("pageSize"));
			} 
		} catch (NumberFormatException e) {
		}
		return pageNumber;
	}

	
}
